package com.novellotus.iov.carvice.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.adapter.RoleHelpAdapter;
import com.novellotus.iov.carvice.bean.RxFindUser;
import com.novellotus.iov.carvice.bean.RxFn;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.utils.TimeUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import okhttp3.RequestBody;

public class AskEmployeeActivity extends BaseActivity {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.nice_spinner)
    NiceSpinner nice_spinner;
    @BindView(R.id.edt_email)
    MaterialEditText edt_email;
    //@BindView(R.id.edt_mobile)
   //MaterialEditText edt_mobile;
    @BindView(R.id.edt_name)
    EditText edt_name;
    @BindView(R.id.edt_mark)
    EditText edt_mark;
    @BindView(R.id.btn_submit)
    Button btn_submit;
    private String eCode = "", rCode = "";
    private ArrayList<RxFn> rxFnList;
    private String id, nickName, roleId, account;
    private Observable<CharSequence> observableNickName;
    private Observable<CharSequence> observableRole;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_ask_employee);
    }

    @Override
    public void init() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            eCode = bundle.getString("e");
            rCode = bundle.getString("r");
            rxFnList = bundle.getParcelableArrayList("roleList");
        }
        if (rxFnList != null) {
            initSpinner();
        }
        tv_tittle.setText("邀请员工");
        setEmailEdit();
        //setMobileEdit();
        setNickNameEdit();
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_submit)
    void submit() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("id", id);
        jsonObject.addProperty("account", account);
        jsonObject.addProperty("nickName", edt_name.getText().toString());
        jsonObject.addProperty("roleId", roleId);
        jsonObject.addProperty("remark", edt_mark.getText().toString());
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/plain; charset=utf-8"), jsonObject.toString());
        Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().askUser(SharedPreferencesUtils.getKey(this)[0], eCode, rCode, body);
        observable.compose(RxSchedulers.<BaseEntity<Object>>compose())
                .subscribe(new BaseObserver<Object>(this) {
                    @Override
                    public void onSuccess(Object rxFindUser) {
                        edt_email.setText("");
                        edt_name.setText("");
                        edt_mark.setText("");
                        MyUtils.showToast(AskEmployeeActivity.this, "邀请成功!");
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        if (code == 400) {
                            edt_name.setText("");
                        }
                        MyUtils.showToast(AskEmployeeActivity.this, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(AskEmployeeActivity.this, msg);
                    }
                });
    }


    /**
     * 设置邮箱编辑框
     */
    private void setEmailEdit() {
        RxTextView.textChanges(edt_email).subscribe(new MyObserver<CharSequence>() {
            @Override
            public void onNext(CharSequence value) {
                super.onNext(value);
                if (MyUtils.isEmail(value.toString()) || MyUtils.isMobile(value.toString())) {
                    account = edt_email.getText().toString();
                    getAccount(account);
                }else{
                    edt_name.setText("");
                    id="";
                }
            }
        });
    }

    @OnClick(R.id.img_help)
    void showHelp() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_role_detail, null);
        RecyclerView recyclerView = view.findViewById(R.id.recycler);
        recyclerView.setLayoutManager(MyViewUtils.getLinearLayoutManager(this));
        recyclerView.setAdapter(new RoleHelpAdapter(rxFnList));
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("角色权限");
        builder.setView(view);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        builder.show();
    }

    /**
     * 设置手机编辑框
     */
//    private void setMobileEdit() {
//        RxTextView.textChanges(edt_mobile).subscribe(new MyObserver<CharSequence>() {
//            @Override
//            public void onNext(CharSequence value) {
//                super.onNext(value);
//                if (edt_mobile.getText().length() == 11) {
//                    if (MyUtils.isMobile(edt_mobile.getText().toString())) {
//                        account = edt_mobile.getText().toString();
//                        getAccount(account);
//                    } else {
//                        edt_mobile.setError("手机格式错误");
//                    }
//                }
//            }
//        });
//    }


    /**
     * 设置昵称编辑框
     */
    private void setNickNameEdit() {
        RxTextView.textChanges(edt_name).subscribe(new MyObserver<CharSequence>() {
            @Override
            public void onNext(CharSequence value) {
                super.onNext(value);
                if (value.toString().length() > 0&&!id.equals("")) {
                    MyViewUtils.setButtonClickable(btn_submit, true);
                } else {
                    MyViewUtils.setButtonClickable(btn_submit, false);
                }
            }
        });
    }


    /**
     * 获取账号信息
     */
    public void getAccount(final String account) {

        Observable<BaseEntity<RxFindUser>> observable = RetrofitFactory.getInstance().findUser(SharedPreferencesUtils.getKey(this)[0], eCode, rCode, account);
        observable.compose(RxSchedulers.<BaseEntity<RxFindUser>>compose())
                .subscribe(new BaseObserver<RxFindUser>(this) {
                    @Override
                    public void onSuccess(RxFindUser rxFindUser) {
                        id = rxFindUser.getId();
                        edt_name.setText(rxFindUser.getNickName());
                        edt_mark.setText(rxFindUser.getRemark());
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        if (code == 400) {
                            edt_name.setText("");
                            id="";
                        }
                        MyUtils.showToast(AskEmployeeActivity.this, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(AskEmployeeActivity.this, msg);
                        id="";
                    }
                });
    }

    private void initSpinner() {
        List<String> dataset = new LinkedList<>();
        for (RxFn rxEinfos : rxFnList) {
            dataset.add(rxEinfos.getRoleName());
        }
        if (dataset.size() == 1) {
            nice_spinner.hideArrow();
        } else {
            nice_spinner.showArrow();
        }
        roleId = rxFnList.get(0).getRoleId();
        nice_spinner.attachDataSource(dataset);
        nice_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                roleId = rxFnList.get(i).getRoleId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }


}
